package jmars.mobile.misc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class OpenElecCell2Geo {

	private static String in="C:\\BaiduYunDownload\\afterprocess\\lac_ci_hash_mapping_rest.txt";
	private static String out="C:\\BaiduYunDownload\\afterprocess\\lac_ci_geolocation_rest.txt";
	
	public static void main(String args[]) throws IOException {
		String row;
		String[] cols;
		FileWriter resultWriter;
		resultWriter = new FileWriter(out);
		File fin = new File(in);
		FileInputStream fis = new FileInputStream(fin);
		BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
		int headercount=0;
		int batch=0;
		String para="";
		String tmpK="";
		String tmpV;
		String[] itemKey,itemValue;
		resultWriter.write("%lac_hash,lac,ci,lat,long,range(m)\r\n");
		while(true){
			row=reader.readLine();
			if(headercount<1){
				headercount++;
				continue;
			}
			if(batch==5||row==null){
				tmpV=getLocation(para);
				itemValue=tmpV.replaceAll("Not found!", "").split("&");
				itemKey=tmpK.split("&");
				for(int i=1;i<itemKey.length;i++){
					resultWriter.write(itemKey[i]+","+itemValue[i]+"\r\n");
				}
				batch=0;
				tmpK="";
				para="";
			}
			if(row==null)break;
			cols=row.split(",");
			if("".equals(para)){
				tmpK=row;
				para="lac="+cols[1]+"&cid="+cols[2];
			}else{
				tmpK=tmpK+"&"+row;
				para=para+"&lac"+batch+"="+cols[1]+"&cid"+batch+"="+cols[2];
				batch++;
			}
			headercount++;
			if(headercount%1000==0)System.out.println(headercount);
		}
		fis.close();
		resultWriter.close();
		System.out.println("finished.");
//		OpenElecCell2Geo.getLocation("33573", "24437");
		
	}
	
	private static String getLocation(String para){
		   
		   String urlmmap = "http://www.open-electronics.org/celltrack/celltxt.php?hex=0&mcc=460&mnc=1&"+para;
		 
		   try {
		       URL url = new URL(urlmmap);
		       HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();      
		       httpConn.setRequestMethod("GET");
		       httpConn.setDoOutput(false);
		       httpConn.setDoInput(true);
		       httpConn.connect();
		       
		       InputStream inputStream = httpConn.getInputStream();
		       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		       String line;
		       while (null != (line = reader.readLine())) {
		    	   return line.substring(0,line.indexOf('<'));
		       }
		       reader.close();
		       inputStream.close();
		       httpConn.disconnect();
		       
		 } catch (IOException e) {
		  // TODO Auto-generated catch block
		  e.printStackTrace();
		 }
		 return null;
		   
	}
	
}
